package cn.com.xy.sms.sdk.service.email;

import java.util.Map;

import org.json.JSONArray;
import org.json.JSONObject;

import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetUtil;
import cn.com.xy.sms.sdk.threadpool.SmartSmsThreadPoolManager;
import cn.com.xy.sms.sdk.util.CallBackState;
import cn.com.xy.sms.sdk.util.StringUtils;
import cn.com.xy.sms.sdk.util.XyUtil;
import cn.com.xy.sms.util.SdkCallBack;

public class EmailService {

    private static int REQUEST_SUCCESS = 0;
    private static int REQUEST_ERROR = -1;
    private static String REQUEST_SUCCESS_CODE = "90001";
    private static int STATUS_HAS_EMAIL_MENU_DATA = 2;
    private static String EMAIL_SERVICE_CRYPT = "3";

    /* KINGMAIL-67 huangzhiqiang 20170411 start */
    /**
     * 根据目的地名称查询目的地所在城市名称
     * 
     * @param destination 火车站名称/飞机场三字代码或者名称
     * @param type 站点类型(0:飞机场 1:火车站)
     * @param extend 扩展参数，可以为空
     * @param sdkCallBack 查询结果回调 
     *                          index0(int类型): 0:成功获取城市名称数据 -1:未能获取城市名称数据 
     *                          index1(String类型): (index0 == 0):城市名称 (index0 == -1):未能获取城市名称数据的原因
     */
    public static void queryCityByDestination(String destination, int type, Map<String, String> extend,
            final SdkCallBack sdkCallBack) {
        requestDestinationInfoByDestinationName(destination, type, extend, new SdkCallBack() {

            @Override
            public void execute(Object... obj) {
                try {
                    int resultCode = (Integer) obj[0];
                    String data = (String) obj[1];
                    if (CallBackState.REQUEST_SUCCESS != resultCode) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, data);
                        return;
                    }

                    if (StringUtils.isNull(data)) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "data is null");
                        return;
                    }

                    JSONObject resultJson = new JSONObject(data);
                    String code = resultJson.optString("code");
                    String content = resultJson.optString("content");
                    if (!REQUEST_SUCCESS_CODE.equals(code)) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, content);
                        return;
                    }

                    JSONArray dataList = resultJson.optJSONArray("dataList");
                    if (dataList == null || dataList.length() == 0) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "no data");
                        return;
                    }

                    JSONObject destinationInfoJson = new JSONObject(dataList.getJSONObject(0).optString("json"));
                    String cityShort = destinationInfoJson.optString("city_short");
                    if (StringUtils.isNull(cityShort)) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "no city data");
                        return;
                    }

                    XyUtil.doXycallBackResult(sdkCallBack, REQUEST_SUCCESS, cityShort);
                } catch (Throwable t) {
                    XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "error:" + t.getMessage());
                    LogManager.e(Constant.TAG, "EmailService queryCityByDestination error", t);
                }
            }
        });
    }

    /**
     * 根据目的地名称获取目的地位置数据
     * 
     * @param destination 火车站名称/飞机场三字代码或者名称
     * @param type 站点类型(0:飞机场 1:火车站)
     * @param extend 扩展参数，可以为空
     * @param sdkCallBack 请求结果回调 
     *            index0(int类型):
     *                  CallBackState.REQUEST_SUCCESS:请求成功
     *                  CallBackState.ERROR:请求出现异常
     *            index1(String类型):
     *                  (index0 == CallBackState.REQUEST_SUCCESS): 地位置数据,例:
     *                           "{\"dataList\":[{\"reqData\":\"凤凰\",\"json\":\"{\\\"city\\\":\\\"三亚市\\\",
     *                        \\\"city_short\\\":\\\"三亚\\\",\\\"code\\\":\\\"SYX\\\",\\\"county\\\":\\\"凤凰市\\\",
     *                        \\\"name\\\":\\\"三亚凤凰国际机场\\\",\\\"province\\\":\\\"海南省\\\",\\\"province_short\\\":
     *                        \\\"海南\\\"}\",\"status\":1}],\"type\":\"airport\",\"version\":\"20161223\",\"code\":
     *                        \"90001\",\"content\":\"成功\"}" }
     *                  (index0 == CallBackState.ERROR):失败说明
     */
    private static void requestDestinationInfoByDestinationName(final String destination, final int type,
            final Map<String, String> extend, final SdkCallBack sdkCallBack) {
        if (sdkCallBack == null) {
            return;
        }
        if (StringUtils.isNull(destination)) {
            XyUtil.doXycallBackResult(sdkCallBack, CallBackState.ERROR, "destination is empty");
            return;
        }
        if (type != 0 && type != 1) {
            XyUtil.doXycallBackResult(sdkCallBack, CallBackState.ERROR, "unknown type");
            return;
        }
        SmartSmsThreadPoolManager.pubInfoPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    // 请求报文数据格式{"reqDatas":[{"reqData":"目的地","city":""}],"type":"airport","allData":"0"}
                    JSONObject postParam = new JSONObject();
                    postParam.put("reqDatas",
                            new JSONArray().put(new JSONObject().put("reqData", destination).put("city", "")));
                    postParam.put("type", (type == 0 ? "airport" : "train"));
                    postParam.put("allData", "0"); // 0为不读取所有机票和火车票信息
                    NetUtil.executeServiceHttpRequest(NetUtil.REQ_TRAVEL, postParam.toString(), extend, false, false,
                            true, sdkCallBack);
                } catch (Throwable t) {
                    XyUtil.doXycallBackResult(sdkCallBack, CallBackState.ERROR, "error:" + t.getMessage());
                    LogManager.e(Constant.TAG, "EmailService requestDestinationInfoByDestinationName error", t);
                }
            }
        });
    }
    /* KINGMAIL-67 huangzhiqiang 20170411 end */

    /* KINGMAIL-49 huangzhiqiang 20170411 start */
    /**
     * 根据邮箱地址查询菜单数据
     * 
     * @param emailAddress 邮箱地址
     * @param extend 扩展参数，可以为空
     * @param sdkCallBack 查询结果回调 
     *                          index0(int类型): 0:成功获取菜单数据 -1:未能获取菜单数据 
     *                          index1:(index0 == 0):(JSONArray类型)菜单数据,例:
     *                       [
     *                           {
     *                               "language": "en",
     *                               "menuItemList": [
     *                                   {
     *                                       "itemCode": "01",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre0011103963969"
     *                                       },
     *                                       "itemName": "economi1",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "02",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001106891616"
     *                                       },
     *                                       "itemName": "economi2",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "03",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-890180737"
     *                                       },
     *                                       "itemName": "economi3",
     *                                       "itemType": "OPEN_URL"
     *                                   }
     *                               ],
     *                               "pubInfoId": "pre001"
     *                           },
     *                           {
     *                               "language": "zh",
     *                               "menuItemList": [
     *                                   {
     *                                       "itemCode": "01",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001570458479"
     *                                       },
     *                                       "itemName": "金融1",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "02",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-426613874"
     *                                       },
     *                                       "itemName": "金融2",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "03",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-1423686227"
     *                                       },
     *                                       "itemName": "金融3",
     *                                       "itemType": "OPEN_URL"
     *                                   }
     *                               ],
     *                               "pubInfoId": "pre001"
     *                           }
     *                       ]
     *                           (index0 == -1):(String类型)未能获取菜单数据的原因
     */
    public static void queryMenuDataByAddress(final String emailAddress, final Map<String, String> extend,
            final SdkCallBack sdkCallBack) {
        requestMenuDataByAddress(emailAddress, extend, new SdkCallBack() {

            @Override
            public void execute(Object... obj) {
                try {
                    int resultCode = (Integer) obj[0];
                    String data = (String) obj[1];
                    if (CallBackState.REQUEST_SUCCESS != resultCode) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, data);
                        return;
                    }

                    if (StringUtils.isNull(data)) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "data is null");
                        return;
                    }

                    JSONObject resultJson = new JSONObject(data);
                    int status = resultJson.optInt("status");
                    String desc = resultJson.optString("desc");
                    if (status != STATUS_HAS_EMAIL_MENU_DATA) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, desc);
                        return;
                    }

                    JSONObject menuDateJson = resultJson.optJSONObject("body");
                    if (menuDateJson == null || menuDateJson.length() == 0) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "no body content");
                        return;
                    }

                    JSONArray menuDataArray = menuDateJson.optJSONArray("menuRelationList");
                    if (menuDataArray == null || menuDataArray.length() == 0) {
                        XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "no menu data");
                        return;
                    }

                    XyUtil.doXycallBackResult(sdkCallBack, REQUEST_SUCCESS, menuDataArray);
                } catch (Throwable t) {
                    XyUtil.doXycallBackResult(sdkCallBack, REQUEST_ERROR, "error:" + t.getMessage());
                    LogManager.e(Constant.TAG, "EmailService queryMenuDataByAddress error", t);
                }
            }
        });
    }


    /**
     * 根据邮箱地址请求菜单数据
     * 
     * @param emailAddress 邮箱地址
     * @param extend 扩展参数，可以为空
     * @param sdkCallBack 请求结果回调 
     *            index0(int类型):
     *                  CallBackState.REQUEST_SUCCESS:请求成功
     *                  CallBackState.ERROR:请求出现异常
     *            index1:
     *                  (index0 == CallBackState.REQUEST_SUCCESS): (JSONObject类型)菜单数据,例:
     *                  "body": {
     *                       "menuRelationList": [
     *                           {
     *                               "language": "en",
     *                               "menuItemList": [
     *                                   {
     *                                       "itemCode": "01",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre0011103963969"
     *                                       },
     *                                       "itemName": "economi1",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "02",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001106891616"
     *                                       },
     *                                       "itemName": "economi2",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "03",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-890180737"
     *                                       },
     *                                       "itemName": "economi3",
     *                                       "itemType": "OPEN_URL"
     *                                   }
     *                               ],
     *                               "pubInfoId": "pre001"
     *                           },
     *                           {
     *                               "language": "zh",
     *                               "menuItemList": [
     *                                   {
     *                                       "itemCode": "01",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001570458479"
     *                                       },
     *                                       "itemName": "金融1",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "02",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-426613874"
     *                                       },
     *                                       "itemName": "金融2",
     *                                       "itemType": "OPEN_URL"
     *                                   },
     *                                   {
     *                                       "itemCode": "03",
     *                                       "itemDetail": {
     *                                           "url": "http://192.168.1.91:8989/get_url_red?xy_key=pre001-1423686227"
     *                                       },
     *                                       "itemName": "金融3",
     *                                       "itemType": "OPEN_URL"
     *                                   }
     *                               ],
     *                               "pubInfoId": "pre001"
     *                           }
     *                       ]
     *                   },
     *                   "desc": "ok",
     *                   "status": 2
     *                  }
     *                  (index0 == CallBackState.ERROR):(String类型)未能获取菜单数据的原因
     */
    private static void requestMenuDataByAddress(final String emailAddress, final Map<String, String> extend,
            final SdkCallBack sdkCallBack) {
        if (sdkCallBack == null) {
            return;
        }
        if (StringUtils.isNull(emailAddress)) {
            XyUtil.doXycallBackResult(sdkCallBack, CallBackState.ERROR, "emailAddress is empty");
            return;
        }
        SmartSmsThreadPoolManager.pubInfoPool.execute(new Runnable() {

            @Override
            public void run() {
                try {
                    Map<String, String> extendMap = extend;
                    if (extendMap == null) {
                        extendMap = NetUtil.getServiceHeaderConfig(EMAIL_SERVICE_CRYPT);
                    } else {
                        extendMap.putAll(NetUtil.getServiceHeaderConfig(EMAIL_SERVICE_CRYPT));
                    }
                    // 请求报文数据格式{ "emailAddress": "邮箱地址" }
                    NetUtil.executeServiceHttpRequest(NetUtil.REQ_EMAIL_MENU,
                            new JSONObject().put("emailAddress", emailAddress).toString(), extendMap, false, false,
                            true, sdkCallBack);
                } catch (Throwable t) {
                    XyUtil.doXycallBackResult(sdkCallBack, CallBackState.ERROR, "error:" + t.getMessage());
                    LogManager.e(Constant.TAG, "EmailService requestMenuDataByAddress error", t);
                }
            }
        });
    }
    /* KINGMAIL-49 huangzhiqiang 20170411 end */
}
